#include <head.h>

int main(int argc, char const *argv[])
{
    char ch;
    int pid_1, pid_2;
    int count = 0;
    int fd = open("123.txt", O_RDONLY, 0666);
    int fd1 = open("123_1.txt", O_RDWR | O_APPEND, 0666);

    if (fd == -1)
    {
        perror("Error opening file");
        return 1;
    }

    lseek(fd, 0, SEEK_SET);

    while (read(fd, &ch, 1) != 0)
    {
        count++;
    }

    printf("%d\n", count / 2);

    if (-1 == (pid_1 = fork()))
    {
        perror("fork error");
        return 0;
    }
    // 父进程
    else if (0 < pid_1)
    {
    }

    // 子进程
    else if (0 == pid_1)
    {
        lseek(fd, 0, SEEK_SET);
        for (size_t i = 0; i < count / 2; i++)
        {
            read(fd, &ch, 1);
            write(fd1, &ch, 1);
        }
    }

    wait(NULL);

    if (-1 == (pid_2 = fork()))
    {
        perror("fork error");
        return 0;
    }
    // 父进程
    else if (0 < pid_2)
    {
    }

    // 子进程
    else if (0 == pid_2)
    {
        lseek(fd, count / 2, SEEK_SET);
        for (size_t i = 0; i <= count ; i++)
        {
            read(fd, &ch, 1);
            write(fd1, &ch, 1);
        }
    }

    wait(NULL);

    close(fd);

    return 0;
}
